<?php

namespace App\Model;

use App\Common\Singleton;
use App\Model\Model;
use Hyperf\Database\Model\SoftDeletes;

class BaseModel extends Model
{
    use Singleton;

    /**
     * 是否开启软删除
     * 开启后 数据表需要有默认的 删除和删除时间字段
     */
    //use softDeletes;

    // 默认开启 创建时间、更新时间自动填充
    // public bool $timestamps = false;

    protected ?string $dateFormat='U';

    // 默认数据表名称
    protected ?string $table='default';
    public function __construct(array $attributes = [])
    {
        // 初始数据表名称
        $this->initTableName();
        parent::__construct($attributes);
    }

    /**
     * Notes: 根据 Model名字 自动生成tableName
     *        要求 命名规范 例如：MemberPointModel -> member_point
     * Author: Bruce.z
     * DateTime: 2024/4/13
     */
    private function initTableName(): void
    {
        if($this->table == 'default'){
            $class = explode( '\\', get_class($this));
            $name = str_replace('Model', '', end($class));
            $this->table = strtolower(preg_replace('/(?<=[a-z])([A-Z])/', '_$1', $name));
        }
    }

    /**
     * Notes: 过滤表字段数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:13
     * @param $data
     */
    public function filterFields(&$data): void
    {
        foreach ($data as $k=>$re){
            if(is_null($re)){unset($data[$k]);}
        }
        $data = array_only($data, $this->fillable);
    }

    /**
     * Notes: 添加数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:17
     * @param $data
     * @return BaseModel|\Hyperf\Database\Model\Model
     */
    public function baseAdd($data): \Hyperf\Database\Model\Model|BaseModel
    {
        $data = array_merge($data, $this->attributes);
        $this->filterFields($data);

        return $this->create($data);
    }

    /**
     * Notes: 根据ID编辑数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:19
     * @param $id
     * @param $data
     * @return int
     */
    public function baseEdit($id, $data): int
    {
        $conditions = $this->attributes;
        return $this->where($conditions)->where($this->primaryKey, '=', $id)->update($data);
    }

    /**
     * Notes: 根据ID删除数据
     * Author: Bruce.z
     * DateTime: 2021/12/21 16:22
     * @param $id
     * @return int|mixed
     */
    public function baseRemove($id): mixed
    {
        $conditions = $this->attributes;
        return $this->where($conditions)->where($this->primaryKey, '=', $id)->delete();
    }

    public function getPrimaryKey(): string
    {
        return $this->primaryKey;
    }
}